package com.bym.mall.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bym.mall.entity.Cart;
import com.bym.mall.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 定时任务配置
 *
 * @author zhaoqiting
 * @date 2022/06/29
 */
@Slf4j
@EnableScheduling
@SpringBootConfiguration
public class SchedulerTaskConfig {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ICartService cartService;

    /**
     * 每日23点30，持久化所有用户的购物车信息
     */
    @Async
    @Scheduled(cron = "0 30 23 * * ?")
    public void persistCartTask() {
        //使用模糊匹配，获取redis中所有用户的购物车
        String likeKey = "CartService:cart:*";
        Set<String> keys = redisTemplate.keys(likeKey);

        //redis中无用户购物车数据
        if (CollectionUtil.isEmpty(keys)) {
            return;
        }

        //持久化所有用户的购物车
        HashOperations<String, String, String> opsForHash = redisTemplate.opsForHash();
        for (String key : keys) {
            //从key中获取uid
            List<String> strs = StrUtil.split(key, ":");
            Integer uid = Integer.valueOf(strs.get(strs.size() - 1));

            Map<String, String> entries = opsForHash.entries(key);
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", uid);
            cartService.remove(queryWrapper);
            ArrayList<Cart> carts = new ArrayList<>();
            for (Map.Entry<String, String> entry : entries.entrySet()) {
                Cart cart = JSONUtil.toBean(entry.getValue(), Cart.class);
                cart.setUserId(uid);
                carts.add(cart);
            }
            cartService.saveBatch(carts);
            redisTemplate.delete(key);
        }
    }
}